package me.zhengjie.modules.sync.processing;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.qiaofang.applet.common.constant.SyncTypeEnum;
import com.qiaofang.applet.common.util.RedisKeyUtil;
import com.qiaofang.applet.common.util.RedisUtil;
import com.qiaofang.applet.common.util.UuidUtil;
import com.qiaofang.applet.constants.UpDownFlagConstants;
import com.qiaofang.applet.constants.VerifyTypeConstants;
import com.qiaofang.applet.service.property.domain.*;
import com.qiaofang.applet.service.property.service.AreaService;
import com.qiaofang.applet.service.property.service.DistrictService;
import com.qiaofang.applet.service.property.service.PropertyDataHandleService;
import com.qiaofang.applet.service.property.service.PropertyService;
import com.qiaofang.common.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.modules.sync.ProcessingBase;
import me.zhengjie.utils.ImageUtil;
import org.apache.poi.ss.usermodel.DateUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author QF2019
 */
@Service
@Slf4j
public class PropertySyncProcessing extends ProcessingBase {

    private static final String PHOTO_CATEGORY = "zipai";

    public PropertySyncProcessing(){
        setDataType(SyncTypeEnum.SALE_AND_RENT.getSyncType());
    }

    @Autowired
    private PropertyService propertyService;
    @Autowired
    private PropertyDataHandleService propertyDataHandleService;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private DistrictService districtService;

    @Autowired
    private AreaService areaService;

    @Override
    public void processing(SyncDataQueue syncDataQueue) {
        List<Property> list= JSON.parseArray(syncDataQueue.getBatchContent(),Property.class);
        if(null==list){
            log.info("processing property is null");
            return;
        }
        list.stream().forEach(item->{
            saveProperty(item,syncDataQueue);
        });
    }

    private void saveProperty(Property item,SyncDataQueue syncDataQueue){
        String propertyUniqueUuid=syncDataQueue.getCompanyUuid()+"_"+item.getPropertyUuid();
        String estateUniqueUuid=syncDataQueue.getCompanyUuid()+"_"+item.getEstateUuid();
        Property property= propertyService.findByPropertyUniqueUuid(propertyUniqueUuid);
        if(!Objects.isNull(item.getDeleted()) && item.getDeleted()){
            if (!Objects.isNull(property)) {
                propertyService.deleteById(property.getId());
            }
            return;
        }
        if(Objects.isNull(property)){
            property=new Property();
            property.setRecommend(false);
        }
        //复制属性
        String[] ignoreProperties=new String[] { "id","recommend", "upDownFlag", "manualUpTime", "updateBy","createTime","updateTime","usageTypeName"};
        BeanUtils.copyProperties(item,property,ignoreProperties);
        //计算楼层范围（高/中/低）字段，规则为实际楼层低于总楼层1/3为低，高于总楼层2/3为高，其余为中层
        property.setFloorRange(getFloorRange(property.getFloor(),property.getTotalFloor()));
        property.setCompanyUuid(syncDataQueue.getCompanyUuid());
        property.setCityCode(syncDataQueue.getCityCode());
        property.setCorporationCode(syncDataQueue.getCorporationCode());
        property.setUpdateTime(new Date());
        property.setLastSyncDate(new Date(System.currentTimeMillis() - DateUtil.DAY_MILLISECONDS));
        //房源描述
        if(!CollectionUtils.isEmpty(item.getPropertyExplainList())){
            PropertyExplain propertyExplainVO = item.getPropertyExplainList().get(0);
            property.setPropertyExplain(propertyExplainVO.getContent());
        }
        try {
            processingPhoto(property);
        } catch (Exception e) {
            log.error("processingPhoto error,propertyUniqueUuid:{}", propertyUniqueUuid, e);
        }
        //处理房源核验二维码图片
        processingVerifyPhoto(property);
        //删除房源图片水印缓存
        redisUtil.hdel(RedisKeyUtil.getPropertyWaterMarkKey(syncDataQueue.getCompanyUuid()), propertyUniqueUuid);

        if (Objects.isNull(property.getUpDownFlag())) {
            //新插入数据 默认下架
            property.setUpDownFlag(UpDownFlagConstants.DOWN_FLAG.getValue());
        }
        //只对有效房源进行上下架处理
        if ("有效".equals(property.getTradeStatus())) {
            property.setRulesHandle(false);
        }
        property.setPropertyUniqueUuid(propertyUniqueUuid);
        property.setEstateUniqueUuid(estateUniqueUuid);
        // 如果是V20的公司，则需要根据房源信息中的城市名字和商圈名字去同城区表和商圈表
        if(syncDataQueue.getV20Flag()) {
            saveDistrictAndArea(syncDataQueue, property);
        }
        try {
            propertyDataHandleService.initPropertyRedundanceField(property);
            property.setRelationUpdate(false);
            propertyService.save(property);
        } catch (Exception e) {
            log.error("saveProperty error,propertyUniqueUuid:{}", propertyUniqueUuid, e);
            //记录错误日志
            this.saveErrorLog(JSON.toJSONString(property),e.getMessage(),syncDataQueue);
        }
    }

    //处理图片相关
    private void processingPhoto(Property property){
        String domainUrl=ImageUtil.HTTP+ImageUtil.IMAGE_URL+"/";
        List<PropertyPhoto>  photoList= property.getPhotoList();
        if(CollectionUtils.isEmpty(photoList)) {
            return;
        }
        List<String> replaceList=new ArrayList<>();

        //如果没有排序字段默认赋值999
        photoList = photoList.stream().map(propertyPhoto -> {
            if (null == propertyPhoto.getPhotoIndex()) {
                propertyPhoto.setPhotoIndex(999);
            }
            return propertyPhoto;
        }).collect(Collectors.toList());

        //先排序
        Collections.sort(photoList, new Comparator<PropertyPhoto>() {
            @Override
            public int compare(PropertyPhoto o1, PropertyPhoto o2) {
                return o1.getPhotoIndex() - o2.getPhotoIndex();
            }
        });

        for(PropertyPhoto propertyPhoto : photoList){
            if(StringUtils.isEmpty(propertyPhoto.getPhotoURL()) || (StringUtil.isNotEmpty(propertyPhoto.getPhotoCategory()) && propertyPhoto.getPhotoCategory().contains(PHOTO_CATEGORY))){
                continue;
            }
            String replaceUrl = propertyPhoto.getPhotoURL();
            if (!replaceUrl.contains(ImageUtil.HTTP) && !replaceUrl.contains(ImageUtil.HTTPS)) {
                replaceUrl = domainUrl + replaceUrl;
            }
            replaceList.add(replaceUrl);
        }

        if(CollectionUtils.isEmpty(replaceList)) {
            return;
        }
        //设置图片集合
        property.setImageUrls(replaceList);
        //设置首图
        if (StringUtil.isEmpty(property.getMainImageUrl())) {
            property.setMainImageUrl(replaceList.get(0));
        }
    }

    //处理房源核验二维码图片
    private void processingVerifyPhoto(Property property){
        if (ObjectUtil.isNull(property.getVerifyType())
                || property.getVerifyType().equals(VerifyTypeConstants.ADDRESS.getVerifyType())) {
            return;
        }
        property.setVerifyQrCode(StringUtils.replace(property.getVerifyQrCode(), ImageUtil.HTTP, ImageUtil.HTTPS));
    }

    private static String minSort(List<PropertyPhoto> vo){
        if(null == vo || vo.isEmpty()){
            return  "";
        }
        Collections.sort(vo,new Comparator<PropertyPhoto>() {
            @Override
            public int compare(PropertyPhoto v1,PropertyPhoto v2){
                if(null==v1.getPhotoIndex() || null==v2.getPhotoIndex()){
                    return 0;
                }
                if(v1.getPhotoIndex() > v2.getPhotoIndex()){
                    return 1;
                }else if(v1.getPhotoIndex() < v2.getPhotoIndex()){
                    return -1;
                }else{
                    return 0;
                }
            }
        });
        return vo.get(0).getPhotoURL();
    }

    private String getFloorRange(String floor,Integer totalFloor){
        if(StringUtils.isEmpty(floor) || Objects.isNull(totalFloor)){
            return "";
        }
        if(!NumberUtil.isInteger(floor)){
            return "";
        }
        if((Integer.valueOf(floor).intValue()*3)<(totalFloor.intValue()*1)){
            return "底层";
        }else if((Integer.valueOf(floor).intValue()*3)>(totalFloor.intValue()*2)){
            return "高层";
        }else{
            return "中层";
        }

    }

    /**
     * 保存城区信息
     * @param property
     * @param syncDataQueue
     * @param property
     */
    private void saveDistrictAndArea(SyncDataQueue syncDataQueue, Property property) {
        String districtName = property.getDistrictName();
        String areaName = property.getAreaName();
        if (StringUtils.isEmpty(districtName)){
            return;
        }
        District district = new District();
        district.setDistrictName(districtName);
        district.setCompanyUuid(syncDataQueue.getCompanyUuid());
        district.setCorporationCode(syncDataQueue.getCorporationCode());
        district.setCityCode(syncDataQueue.getCityCode());
        Optional<District> optional = districtService.findOne(Example.of(district));
        String districtUuid;
        if(optional.isPresent()) {
            districtUuid = optional.get().getDistrictUuid();
            property.setDistrictUuid(districtUuid);
        }else {
            districtUuid = UuidUtil.geneUuidString();
            district.setDistrictUuid(districtUuid);
            district.setDeleted(false);
            district.setRelationUpdate(false);
            district.setLastSyncDate(new Date());
            districtService.save(district);
            property.setDistrictUuid(districtUuid);
        }
        if (StringUtil.isEmpty(areaName)) {
            return;
        }
        property.setAreaUuid(saveArea(syncDataQueue, districtUuid, areaName));
    }

    /**
     * 保存商圈信息
     * @param districtUuid
     * @param areaName
     * @param syncDataQueue
     */
    private String saveArea(SyncDataQueue syncDataQueue, String districtUuid, String areaName) {
        Area area = new Area();
        area.setAreaName(areaName);
        area.setDistrictUuid(districtUuid);
        area.setCompanyUuid(syncDataQueue.getCompanyUuid());
        area.setCorporationCode(syncDataQueue.getCorporationCode());
        area.setCityCode(syncDataQueue.getCityCode());
        Optional<Area> optional = areaService.findOne(Example.of(area));
        if(optional.isPresent()) {
            return optional.get().getAreaUuid();
        }
        String areaUuid = UuidUtil.geneUuidString();
        area.setAreaUuid(areaUuid);
        area.setDeleted(false);
        area.setRelationUpdate(false);
        area.setLastSyncDate(new Date());

        areaService.save(area);
        return areaUuid;
    }

}
